package com.leyou.user.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


@Service
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;
    //图片格式过滤常量
    private static final List<String> CONTENT_TYPE = Arrays.asList(
            "image/jpeg", "image/gif", "image/jpeg", "image/jpg"
    );
    //日志打印，完成提示-slf4j
    private static final Logger MYLOGGER = LoggerFactory.getLogger(UploadService.class);

    /**
     * 上传图片
     * MultipartFile是文件上传的SpringMvc封装类
     *
     * @param file 文件
     * @return {@link ResponseEntity}<{@link String}>
     */
    public String upload(MultipartFile file) {
        //校验文件类型--{}是占位符号
        String originalFilename = file.getOriginalFilename();//文件原始名字
        String contentType = file.getContentType();//文件头信息包含文件的属性
        if (!CONTENT_TYPE.contains(contentType)) {
            MYLOGGER.info("文件不合法，{}", originalFilename);
            return null;
        }
        //校验文件内容-imageIo类-这个名字的包
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                MYLOGGER.info("文件内容不合法，{}", originalFilename);
                return null;
            }
            //文件保存注意路径符号-本机-nginx图片服务器
//            file.transferTo(new File("D:\\userimage\\"+originalFilename));
            //获取后缀
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            //上传成功返回路径--fastdfs,返回带组信息的文件位置
//            return "http://image.leyou.com/" + originalFilename;
            return "http://image.leyou.com/" + storePath.getFullPath();

        } catch (IOException e) {
            MYLOGGER.error("服务器内部错误,{}", originalFilename);
            e.printStackTrace();
        }
        return null;
        //获取url回显

    }
}
